package com.topisv.tms.utils.http;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.topisv.tms.entity.Costinfo;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.GoodCostinfo;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.utils.vo.HtSendOutVo;
import com.topisv.tms.utils.vo.RestAreaGroupVo;
import com.topisv.tms.utils.vo.RestCustomersAreagroupVo;

import net.sf.json.JSONObject;

public abstract class HttpPost {
	
	private static final Logger log = LoggerFactory.getLogger(HttpPost.class);
	
	/**
	 * TMS取消订单
	 * @param customers
	 * @param ordeno
	 * @return
	 * @throws Exception
	 */
	public static String bmsCancelOrdeno(Customers customers,String ordeno)throws Exception{
		try {
			StringBuffer sb=new StringBuffer();
			sb.append("customerCode="+customers.getCustomerCode());
			sb.append("&ordeno="+ordeno);
			String result=pub(customers.getCancelUrl(), sb.toString());
			return result;
		} catch (Exception e) {
			throw e;
		}
	}
	
	/**
	 * 禾塘发货
	 * @param ediOrder
	 * @param shopSource
	 * @return
	 * @throws Exception
	 */
	public static HtSendOutVo htSendOutGoods(EdiOrder ediOrder,ShopSource shopSource)throws Exception{
		log.info(ediOrder.getOrdeno()+"：订单发货开始");
		String result="";
		HtSendOutVo htSendOutVo=null;
		try {
			String customersOrdeno=ediOrder.getCustomerOrdeno();
			String[] ordenos=customersOrdeno.split(":");
			for(String o:ordenos){
				if(!"".equals(o)){
					StringBuffer sb=new StringBuffer();
					sb.append("orderCode="+o);
					sb.append("&expressCode="+ediOrder.getWaybillNo());
					sb.append("&appkey="+shopSource.getHtStockUser());
					sb.append("&appsecret="+shopSource.getHtStockSign());
					sb.append("&logisticCode=ESB");
				    log.info("参数名:"+sb.toString());
					result = pub(shopSource.getHtSendUrl(), sb.toString());
					log.info("调用订单返回值："+result);
					JSONObject json = JSONObject.fromObject(result);
					htSendOutVo=(HtSendOutVo) JSONObject.toBean(json, HtSendOutVo.class);
				}
			}
			
			return htSendOutVo;
		} catch (Exception e) {
			throw e;
		}
	}
	
	
	/**
	 * 根据商家编码获得网点信息
	 * 
	 * @param customersCode
	 * @return
	 * @throws Exception
	 */
	public static RestCustomersAreagroupVo getRestCustomersAreagroupVo(Customers customers) throws Exception {
		try {
			String result = HttpPost.ajaxAreaGroup(customers);
			JSONObject json = JSONObject.fromObject(result);
			if ("1".equals(json.get("status"))) {
				@SuppressWarnings("rawtypes")
				Map<String, Class> maps = new HashMap<String, Class>();
				maps.put("restAreaGroupDtos", RestAreaGroupVo.class);
				
				RestCustomersAreagroupVo restCustomersAreagroupVo = (RestCustomersAreagroupVo) JSONObject
						.toBean(JSONObject.fromObject(result).getJSONObject("content"), RestCustomersAreagroupVo.class, maps);
				
				return restCustomersAreagroupVo;
			}
			return null;
		} catch (Exception e) {
			throw e;
		}
	}
	
	/**
	 * 根据sku查询库存信息
	 * @param ordenoSourceCode
	 * @param skuId
	 * @return
	 * @throws Exception
	 */
	public static GoodCostinfo getGoodCostinfo(ShopSource shopSource,String skuId)  throws Exception{
		log.info("根据sku获得库存信息开始");
		String user = shopSource.getHtStockUser();
		String barCodeAddress = shopSource.getHtStockSku();
		String sign = shopSource.getHtStockSign();
		String param="user="+user+"&sign="+sign+"&barcode="+skuId;
		log.info("ERP地址:"+barCodeAddress);
		log.info("ERP地址参数:"+param);
		String result=null;
		GoodCostinfo obj=null;
		try {
			result = pub(barCodeAddress, param);
			log.info("ERP返回结果:"+result);
			JSONObject json=JSONObject.fromObject(result);
			Object object=json.get("GoodsCostInfo");
			Map<String, Class<Costinfo>> classMap=new HashMap<String, Class<Costinfo>>();
			classMap.put("costList", Costinfo.class);
			obj=(GoodCostinfo) JSONObject.toBean(JSONObject.fromObject(object), GoodCostinfo.class, classMap);
		} catch (Exception e) {
			log.error("error",e);
			throw e;
		}
		return obj;
	}
	
	/**
	 * 模拟POST请求访问
	 * @param serviceURL
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public static String pub(String serviceURL) throws Exception {
		URL url = null;
		HttpURLConnection connection = null;
		StringBuffer buffer = new StringBuffer();
		try {
			url = new URL(serviceURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Accept-Charset","utf-8");
			OutputStream os=connection.getOutputStream();
	        DataOutputStream dos=new DataOutputStream(os);
	        dos.flush();
	        dos.close(); 
			InputStream inputStream = connection.getInputStream();
			byte[] bytes = new byte[1024];
			int count = inputStream.read(bytes);
			while (count != -1) {
				buffer.append(new String(bytes, 0, count, "GBK"));
				count = inputStream.read(bytes);
			}
			inputStream.close();
		} catch (Exception e) {
			throw e;
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return buffer.toString();
	}
	

	/**
	 * 模拟POST请求访问
	 * @param serviceURL
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public static String pub(String serviceURL, String param) throws Exception {
		URL url = null;
		HttpURLConnection connection = null;
		StringBuffer buffer = new StringBuffer();
		try {
			url = new URL(serviceURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Length",param.length()+"");
			OutputStream os=connection.getOutputStream();
	        DataOutputStream dos=new DataOutputStream(os);
	        dos.write(param.getBytes("UTF-8"));
	        dos.flush();
	        dos.close(); 
			InputStream inputStream = connection.getInputStream();
			byte[] bytes = new byte[1024];
			int count = inputStream.read(bytes);
			while (count != -1) {
				buffer.append(new String(bytes, 0, count, "UTF-8"));
				count = inputStream.read(bytes);
			}
			inputStream.close();
		} catch (Exception e) {
			throw e;
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return buffer.toString();
	}
	
	/**
	 * 根据客户编码获得客户网点信息
	 * @param customerCode
	 * @return
	 * @throws Exception
	 */
	public static String ajaxAreaGroup(Customers customers) throws Exception{
		String param="username="+customers.getAreasUsername()+"&password="+customers.getAreasPassword()+"&customerCode="+customers.getCustomerCode();
		log.info("TMS地址:"+customers.getAreasGroupInf());
		log.info("TMS地址参数:"+param);
		String result=null;
		try {
			result = pub(customers.getAreasGroupInf(), param);
			log.info("TMS地址返回参数:"+result);
		} catch (Exception e) {
			log.error("error",e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 出库批次信息
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public static String putShippedBatch(Customers customers,String content)throws Exception{
		log.info("出库批次推送开始");
		String address = customers.getTmsBatchAddress();
		String param="appkey="+customers.getTmsBatchAppkey()+"&appsecret="+customers.getTmsBatchAppsecret()+"&data="+content;
		log.info("出库批次推送地址:"+address);
		log.info("出库批次推送地址参数:"+param);
		String result=null;
		try {
			result = pub(address, param);
			log.info("出库批次推送地址返回参数:"+result);
		} catch (Exception e) {
			log.error("error",e);
			throw e;
		}
		return result;
	}
	
	public static String putForwardBatch(Customers customers,String content)throws Exception{
		log.info("出库批次推送开始");
		String address = customers.getForwardBatchAddress();
		String param="appkey="+customers.getTmsBatchAppkey()+"&appsecret="+customers.getTmsBatchAppsecret()+"&data="+content;
		log.info("出库批次推送地址:"+address);
		log.info("出库批次推送地址参数:"+param);
		String result=null;
		try {
			result = pub(address, param);
			log.info("出库批次推送地址返回参数:"+result);
		} catch (Exception e) {
			log.error("error",e);
			throw e;
		}
		return result;
	}
}
